#include "FrameWindow.h"

namespace Zaf {
namespace Mwl {



void FrameWindow::InitializeFrameWindow(CreatedEventArgs& args) {
	::SetWindowLong(GetHandle(), DWL_DLGPROC, (LONG)FrameWindow::OrignalDlgProc);
}



DWORD FrameWindow::ShowModal() {

	m_isModal = true;

	::EnableWindow(m_owner, false);
	::ShowWindow(GetHandle(), SW_SHOW);

	MSG msg;
	while (GetMessage(&msg, NULL, 0, 0)) {

		if (IsDialogMessage(GetHandle(), &msg) == FALSE) {

			TranslateMessage(&msg);
			DispatchMessage(&msg);
		}
	}

	DestroyWindow(GetHandle());

	::EnableWindow(m_owner, true);
	::SetForegroundWindow(m_owner);

	m_isModal = false;
	m_owner = NULL;

	return m_dialogResult;
}



void FrameWindow::Close() {
	SendMessage(GetHandle(), WM_CLOSE, 0, 0);
}



LRESULT FrameWindow::DefWndProc(const WndMsg& msg) {

	return ::CallWindowProc(DefDlgProc, msg.Hwnd, msg.Message, msg.WParam, msg.LParam);
}



LRESULT FrameWindow::WndProc(const WndMsg& msg) {

	switch (msg.Message) {

		case WM_CLOSE:
			if (m_isModal == true) {
				EndModal(IDCANCEL);
			}
			else {
				DestroyWindow(GetHandle());
				if (m_owner != NULL) {
					::SetFocus(m_owner);
					m_owner = NULL;
				}
			}
			return 0;
	}

	return Window::WndProc(msg);
}



BOOL FrameWindow::DlgProc(const WndMsg& msg) {

	return FALSE;
}



BOOL CALLBACK FrameWindow::OrignalDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) {

	FrameWindow* frame = dynamic_cast<FrameWindow*>((Window*)GetWindowLong(hwnd, GWL_USERDATA));

	if (frame == nullptr) {
		return FALSE;
	}

	WndMsg wndMsg(hwnd, msg, wParam, lParam);

	return frame->DlgProc(wndMsg);
}


}
}